package cn.suimg.bilibili.util;


import java.util.Arrays;

public class HexUtil {

    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        StringBuffer fsb = new StringBuffer("\n");
        String org = sb.toString().replaceAll("(.{4})","$1  ").replaceAll("(.{48})","$1\n");
        Arrays.asList(org.split("\n")).forEach(o -> {
            int appendSpace = 48 - o.length();
            StringBuffer tsb = new StringBuffer();
            Arrays.asList(o.split("  ")).forEach(h -> {
               tsb.append((hexToAscii(h)+"  ").replace("\n",""));
            });
            if(appendSpace!=0){
                StringBuffer asb = new StringBuffer(o);
                for(int i=0;i<appendSpace;i++){
                    asb.append(" ");
                }
                o=asb.toString();
            }

            fsb.append(String.format("%s |   %s\n",o,tsb.toString()));
        });
        return fsb.toString();
    }

    private static String hexToAscii(String hexStr) {
        StringBuilder output = new StringBuilder("");
        for (int i = 0; i < hexStr.length(); i += 2) {
            String str = hexStr.substring(i, i + 2);
            output.append((char) Integer.parseInt(str, 16));
        }
        return output.toString();
    }

    public static int byteArrayToInt(byte[] bytes) {
        int value=0;
        for(int i = 0; i < 4; i++) {
            int shift= (3-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }
}
